/**
 * 政区上溯与下钻
 */
define([
    "map","getZQShuttledata"
], function(map, getzqdata) {
    'use strict';
    let currentLevel = undefined;// 记录当前的边界的level
    let parentcode = undefined;// 记录最后一次的政区代码
    let isUsing = false;
    let _highlightFeature = null;

    let popHtml = '<div id="popup" class="ol-popup" style="display: none;">' +
                     '<div id="popup-content"></div>' +
                  '</div>';
    let container = null;
    let content = null;

    let olmap = map.getMap();
    let GeoJSONFormat = new ol.format.GeoJSON();

    let popupOverlay = null;
    let bordervectorLayerSource = null;
    let bordervectorLayer = null;// 边界图层
    let contentvectorLayerSource = null;
    let contentvectorLayer = null;// 内部政区图层
    let styleCollection = {
        borderStyle: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: '#000',
                width: 2
            })
        }),
        highlightStyle: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: '#000',
                width: 1,
                lineDash: [10]
            }),
            fill: new ol.style.Fill({
                color: 'rgba(11, 95, 255, 0.8)'
            })
        }),
        generalStyle: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: '#000',
                width: 1,
                lineDash: [10]
            }),
            fill: new ol.style.Fill({
                color: 'rgba(230, 230, 230, 0.8)'
            })
        })
    };

    let _serverUrl = "./geoLocation";
    let isinit = false;
    let maxLevel = 3;
    let minLevel = 1;

    let getPopHtmlByfeature = null;

    /**
     * 
     * @param {String} code 初始化时的zqcode 
     * @param {String} serverUrl geoLocation地址
     */
    function init(params) {
        if (isinit) {
            return isinit;
        }
        _serverUrl = params["serverUrl"] || _serverUrl;
        getPopHtmlByfeature = params["popFun"] || getPopHtmlByfeature;
        styleCollection = params["styleCollection"] || styleCollection;
        styleCollection = params["styleCollection"] || styleCollection;
        styleCollection = params["styleCollection"] || styleCollection;
        initUi();
        getzqdata.init(_serverUrl);
        initLayer();
        bindEvent();
        isinit = true;// 初始化完成
        if (params["code"]) {
            setvectorLayerByCode(params["code"]);
        }
        return false;
    }

    function initLayer() {
        $(container).show();
        popupOverlay = new ol.Overlay({
            element: container
        });
        olmap.addOverlay(popupOverlay);

        bordervectorLayerSource = new ol.source.Vector()
        bordervectorLayer = new ol.layer.Vector({
            source: bordervectorLayerSource,
            zIndex: 102,
            opacity: 1,
            visible: false,
            style: styleCollection.borderStyle
        });
        map.addLayer("bordervectorLayer", bordervectorLayer);
    
        contentvectorLayerSource = new ol.source.Vector();
        contentvectorLayer = new ol.layer.Vector({
            source: contentvectorLayerSource,
            zIndex: 101,
            opacity: 1,
            visible: false,
            style: getStyleByfeature
        });
        map.addLayer("contentvectorLayer", contentvectorLayer);
    }

    function initUi() {
        $("body").append(popHtml);
        container = document.getElementById('popup');
        content = document.getElementById('popup-content');
    }

    function getStyleByfeature(fea) {
        if (fea.get("ishighlight")) {
            return styleCollection.highlightStyle;
        }
        return styleCollection.generalStyle;
    }

    function getFeatureBypixel(pixel) {
        let features = olmap.getFeaturesAtPixel(pixel, {layerFilter: function (layer){
            return layer.get("c_layerId") === "contentvectorLayer"
        }});
        return features ? features[0] : null;
    }

    function bindEvent() {
        olmap.on("pointermove", showPop)
        olmap.on("dblclick", shuttleZq)
    }

    // 鼠标经过显示弹窗并高亮图斑
    function showPop(e) {
        if (isUsing) {
            let feature = getFeatureBypixel(e.pixel);
            if (feature) {
                isDohighlight(feature) && (highlightFea(feature), popUpFun(feature));
            }else {
                cancelhighlight();
            }
        }
    }

    /**
     * @Description : 是否高亮feature
     * @Author : houhuawei
     * @Date : 2023-02-13 14:29:57
     * @param {feature} fea 
     * @return {boolean}  
     */ 
    function isDohighlight(fea) {
        if(!fea) return false;
        return _highlightFeature ? _highlightFeature.get("code") !== fea.get("code") : true;
    }

    // 高亮操作
    function highlightFea(fea) {
        _highlightFeature && _highlightFeature.set("ishighlight", false);
        fea.set("ishighlight", true);
        _highlightFeature = fea;
    }

    // 弹窗信息
    function popUpFun(fea) {
        let extent = fea.getGeometry().getExtent();
        let coordinate = [(extent[0] + extent[2])/2, extent[3]];
        content.innerHTML = getPopHtmlByfeature(fea);
        popupOverlay.setPosition(coordinate);
    }

    getPopHtmlByfeature = function (fea) {
        return '<div>code：' + fea.get("code") +'</div>' + '<div>name：' + fea.get("name") +'</div>';
    }

    // 取消高亮
    function cancelhighlight() {
        _highlightFeature && _highlightFeature.set("ishighlight", false);
        _highlightFeature = null;
        popupOverlay.setPosition(undefined);
    }

    // 下钻与上溯
    function shuttleZq(e) {
        if (isUsing) {
            let feature = getFeatureBypixel(e.pixel);
            feature ? (drillDown(feature)) : (rollUp());
            // if (afterShuttle) {
            //     afterShuttle({
            //         lastCode: "",
            //         currentCode: ""
            //     });
            // }
        }
    }

    // 下钻
    function drillDown(feature) {
        feature.get("level") < maxLevel && setvectorLayerByCode(feature.get("code"), true);
    }

    // 上溯
    function rollUp() {
        currentLevel > minLevel && setvectorLayerByCode(parentcode, true);
    }

    // 获取政区数据并添加feature
    function setvectorLayerByCode(code, islocation) {
        let zqdata = getzqdata.getdata(code);
        bordervectorLayerSource.clear();
        contentvectorLayerSource.clear();
        contentvectorLayerSource.addFeatures(getFeaturesBydata(zqdata.child));
        bordervectorLayerSource.addFeatures(getFeaturesBydata([zqdata.item]));
        if (islocation) {
            let extent = zqdata.item.extent
            if (typeof extent === "string") {
                extent = JSON.parse(zqdata.item.extent)
            }
            let initextent = [...extent];
            olmap.getView().fit(initextent);
        }
        currentLevel = zqdata.item.level + 1;
        parentcode = zqdata.item.pid;
    }

    // 生成feature
    function getFeaturesBydata(matedatas) {
        let feas = [];
        matedatas.forEach(item => {
            let fea = GeoJSONFormat.readFeature(item.shape);
            Object.keys(item).forEach(field => {
                field !== "shape" && fea.set(field, item[field]);
            })
            feas.push(fea);
        })
        return feas
    }


    function setVisible(isshow) {
        if (isinit) {
            cancelhighlight();
            bordervectorLayer.setVisible(isshow);
            contentvectorLayer.setVisible(isshow);
            if (isshow && bordervectorLayerSource.getExtent()[0] != "Infinity") {
                olmap.getView().fit(bordervectorLayerSource.getExtent());
            }
            isUsing = isshow;
        }
    }

    function destory() {
        olmap.removeOverlay(popupOverlay);
        bordervectorLayerSource.clear();
        contentvectorLayerSource.clear();
        map.removeLayer("contentvectorLayer");
        map.removeLayer("bordervectorLayer");
        olmap.un("pointermove", showPop);
        olmap.un("dblclick", shuttleZq);
        isinit = false;
    }

    return{
        init: init,
        setVisible: setVisible,
        destory: destory,
    }
});